package kit.docker.convert;

import com.jfinal.kit.StrKit;
import org.apache.commons.beanutils.BeanUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class ConvertKit {

    public static <T> T mapToObject(Map<String, Object> map, Class<T> clazz) {
        return mapToObjectStr(mapTomap(map), clazz);
    }

    public static <T> T mapToObjectStr(Map<String, String> map, Class<T> clazz) {
        try {
            T t = clazz.newInstance();
            BeanUtils.populate(t, map);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Map<String, String> objectToMap2(Object obj) {
        try {
            return BeanUtils.describe(obj);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Object转Map(反射机制方式)
     *
     * @param obj 要转换的Object
     * @return 转换后的Map
     */
    public static Map<String, Object> objectToMap(Object obj) {
        if (obj == null) {
            return null;
        }

        Map<String, Object> map = null;
        try {
            map = new HashMap<>();

            Field[] declaredFields = obj.getClass().getDeclaredFields();
            for (Field field : declaredFields) {
                field.setAccessible(true);

                // map.put(field.getName(), field.get(obj));
                PropertyDescriptor pd = new PropertyDescriptor(field.getName(), obj.getClass());
                Method getMethod = pd.getReadMethod();
                map.put(field.getName(), getMethod.invoke(obj));

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    public static Map<String, String> mapTomap(Map<String, Object> objMap) {
        Map<String, String> map = new HashMap<>();
        for (String key : objMap.keySet()) {
            map.put(key, StrKit.notNull(objMap.get(key)) ? objMap.get(key).toString() : "");
        }
        return map;
    }

}
